﻿using System.Security.Cryptography;
using System.Text;

namespace Tyche.Common.Util.Utils
{
    public class EncryptUtil
    {
        /// <summary>
        /// 私有构造函数
        /// </summary>
        private EncryptUtil()
        {
        }

        /// <summary>
        /// MD5
        /// </summary>
        /// <param name="clearText"></param>
        /// <returns></returns>
        public static string MD5(string clearText)
        {
            using (var provider = new MD5CryptoServiceProvider())
            {
                return ConvertBytesToString(provider.ComputeHash(Encoding.UTF8.GetBytes(clearText)));
            }
        }

        /// <summary>
        /// SHA256
        /// </summary>
        /// <param name="clearText"></param>
        /// <returns></returns>
        public static string SHA1(string clearText)
        {
            using (var provider = new SHA1CryptoServiceProvider())
            {
                return ConvertBytesToString(provider.ComputeHash(Encoding.UTF8.GetBytes(clearText)));
            }
        }

        /// <summary>
        /// SHA256
        /// </summary>
        /// <param name="clearText"></param>
        /// <returns></returns>
        public static string SHA256(string clearText)
        {
            using (var provider = new SHA256CryptoServiceProvider())
            {
                return ConvertBytesToString(provider.ComputeHash(Encoding.UTF8.GetBytes(clearText)));
            }
        }

        /// <summary>
        /// HMACSHA256
        /// </summary>
        /// <param name="clearText"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public static string HMACSHA256(string clearText, string secret = "")
        {
            using (var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secret)))
            {
                return ConvertBytesToString(hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(clearText)));
            }
        }

        /// <summary>
        /// 字节转成字符
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ConvertBytesToString(byte[] bytes)
        {
            var builder = new StringBuilder();

            for (int i = 0; i < bytes.Length; i++)
            {
                builder.Append(bytes[i].ToString("x2"));
            }

            return builder.ToString();
        }
    }
}
